package com.cws.backup.factory.impl;

import cn.hutool.core.date.DateUtil;
import com.cws.backup.constant.Command;
import com.cws.backup.entity.BackupEntity;
import com.cws.backup.factory.BackupHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;

/**
 * oracle
 *
 * @author cws
 */
@Slf4j
public class OracleBackupHandler implements BackupHandler {
    @Override
    public void backup(BackupEntity backupEntity) {
        log.info("开始执行{}备份...", backupEntity.toString());
        String dumpFile = DateUtil.format(new Date(), "yyyyMMdd_HHmmss") + "_" + backupEntity.getTableSpace() + ".dump";
        String logFile = DateUtil.format(new Date(), "yyyyMMdd_HHmmss") + "_" + backupEntity.getTableSpace() + ".log";
        String command = Command.ORACLE_COMMAND
                .replaceAll("#\\{username}", backupEntity.getUsername())
                .replaceAll("#\\{password}", backupEntity.getPassword())

                .replaceAll("#\\{db}", backupEntity.getDb())
                .replaceAll("#\\{location}", backupEntity.getLocation())
                .replaceAll("#\\{dump}", dumpFile)
                .replaceAll("#\\{log}", logFile)
                .replaceAll("#\\{tablespace}", backupEntity.getTableSpace());

        log.info(command);
        try {
            Process exec = Runtime.getRuntime().exec(command);
            if (exec.waitFor() != 0) {
                InputStream is = exec.getErrorStream();
                if (is != null) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(is, System.getProperty("os.name").startsWith("Win") ? "GBK" : "UTF-8"));
                    String line;
                    StringBuilder sb = new StringBuilder();
                    while ((line = in.readLine()) != null) {
                        sb.append(line);
                    }
                    log.info("备份失败,原因:" + sb);
                    return;
                }
                log.info("备份失败,exec.waitFor=" + exec.waitFor());
                return;
            }
        } catch (Exception e) {
            log.info("备份异常:" + e.getMessage());
            return;
        }
        log.info("备份成功!");
    }
}
